#include "GetHIDDevice.h"


HID_Device hiddevice;

BOOL FindHidDevice(HID_Device *Device) {
    GUID HidGuid = {0x36fc9e60,0xc465,0x11cf,{0x80,0x56,0x44,0x45,0x53,0x54,0x00,0x00}};
    HDEVINFO hDEVInfoSet;
    SP_DEVICE_INTERFACE_DATA DevInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA pDevDetailData;
    //        PSP_DEVINFO_DATA Deviceinfo;
    HIDD_ATTRIBUTES DevAttributes;
    DWORD RequiredSize;
    BOOL Result;
    DWORD MemberIndex = 0;
    //        DWORD FoundDevice_Num = 0;
    DevInterfaceData.cbSize = sizeof(DevInterfaceData);
    DevAttributes.Size = sizeof(DevAttributes);
    HidD_GetHidGuid(&HidGuid);
    hDEVInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );
    while (TRUE) {
        //            SetupDiEnumDeviceInfo(hDEVInfoSet,MemberIndex,Deviceinfo);
        //            qDebug() << "GUID :" << Deviceinfo->ClassGuid.Data1 << Deviceinfo->ClassGuid.Data2 << Deviceinfo->ClassGuid.Data3 << Deviceinfo->ClassGuid.Data4;
        Result = SetupDiEnumDeviceInterfaces(hDEVInfoSet, NULL, &HidGuid, MemberIndex, &DevInterfaceData);
        if (Result == FALSE)
            break;
        MemberIndex++;
        Result = SetupDiGetDeviceInterfaceDetail(hDEVInfoSet, &DevInterfaceData, NULL, NULL, &RequiredSize, NULL);
        if(Result == FALSE){
//            qDebug() << "ERROR: " <<GetLastError();
//                continue;
        }
        pDevDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
        if (pDevDetailData == NULL) {
            SetupDiDestroyDeviceInfoList(hDEVInfoSet);
            return FALSE;
        }
        pDevDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
        Result = SetupDiGetDeviceInterfaceDetail(hDEVInfoSet, &DevInterfaceData, pDevDetailData, RequiredSize, NULL, NULL);
        //            qDebug() << "HID Index：" << MemberIndex << "Path:" << pDevDetailData->DevicePath ;
        if (Result == FALSE)
            continue;
        Device->Device = CreateFile(pDevDetailData->DevicePath, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0 , NULL);
        free(pDevDetailData);
        if (Device != INVALID_HANDLE_VALUE) {
            Result = HidD_GetAttributes(Device->Device, &DevAttributes);
            if (Result == FALSE)
                continue;
            if (DevAttributes.VendorID == Device->VID) {
                Device->PID = DevAttributes.ProductID;
                Device->VID = DevAttributes.VendorID;
                return Result;
                //DeviceIoControl(Device, IOCTL_HID_SET_FEATURE, &buffer, 50, &outbuffer, 50, NULL, NULL);
                //DeviceIoControl(Device, IOCTL_HID_GET_FEATURE, &buffer, 50, &outbuffer, 50, NULL, NULL);
            }else{
                Device->PID = DevAttributes.ProductID;
            }
        }else{
            qDebug() << GetLastError();
        }
    }

    return Result;
}

HID_Device GetDevice(){
    return hiddevice;
}

